package com.ragdollcat.thirdaicodegenerate.core;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.ragdollcat.thirdaicodegenerate.ai.model.HtmlCodeResult;
import com.ragdollcat.thirdaicodegenerate.ai.model.MultiFileCodeResult;
import com.ragdollcat.thirdaicodegenerate.enums.CodeGenTypeEnum;

import java.io.File;

/**
 * 保存生成的文件到本地
 * 文件路径：tmp/code/bizType_雪花Id/文件名
 */
public class CodeFileSaver {

    /**
     * 基本路径，在本地是
     * D:\Idea_workspace\2025\third-ai-code-generate\tmp\code
     */
    public static final String DEFAULT_PATH = System.getProperty("user.dir") + java.io.File.separator + "tmp" + File.separator + "code";


    /**
     * 保存html文件
     *
     * @param htmlCodeResult
     * @return
     */
    public static File saveHtmlCode(HtmlCodeResult htmlCodeResult) {
        String path = DEFAULT_PATH + makeUniqueContents(CodeGenTypeEnum.HTML.getValue());
        doSave(path + File.separator + "html.txt", htmlCodeResult.getHtmlCode());
        return new File(path);
    }

    /**
     * 保存原生多文本
     *
     * @param multiFileCodeResult
     * @return
     */
    public static File saveMutliFileCode(MultiFileCodeResult multiFileCodeResult) {
        String path = DEFAULT_PATH + makeUniqueContents(CodeGenTypeEnum.MULTI_FILE.getValue());
        doSave(path + File.separator + "html.txt", multiFileCodeResult.getHtmlCode());
        doSave(path + File.separator + "css.txt", multiFileCodeResult.getCssCode());
        doSave(path + File.separator + "js.txt", multiFileCodeResult.getCssCode());
        return new File(path);
    }





    /**
     * 进行保存
     *
     * @param path    保存的路径
     * @param content 文件内容
     */
    public static void doSave(String path, String content) {
        FileUtil.writeUtf8String(content, path);
    }

    /**
     * 制作唯一的目录，利用业务编码和雪花ID
     *
     * @param bizType
     * @return
     */
    private static String makeUniqueContents(String bizType) {
        return bizType + "_" + IdUtil.getSnowflakeNextIdStr();
    }
}
